
<template>
  <div class="execution">
    <basic-container>
      <report
        v-if="showReport"
        @exit="showReport = false"
      >
      </report>
      <avue-crud
        v-else
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @selection-change="selectionChange"
      >
        <template
          slot="cleanTime"
          slot-scope="{row}"
        >
          {{row.beginTime}}~{{row.endTime}}
        </template>
        <template slot="diffMoneySearch">
          <el-col :span="24">
            <el-input-number
              placeholder="最小值"
              style="width: 45%"
              :controls="false"
              v-model="extraParam.diffMoneyStart"
            ></el-input-number>
            -
            <el-input-number
              placeholder="最大值"
              style="width: 45%"
              :controls="false"
              v-model="extraParam.diffMoneyEnd"
            ></el-input-number>
          </el-col>
        </template>
        <template slot="menuRight">
         <!-- 
	  <el-button
            size="small"
            v-if="permissionList.viewReportBtn"
            @click="showReport = true"
            hidden = "true"
          >查看调整报表</el-button>
          <el-button
            type="primary"
            size="small"
            v-if="permissionList.confirmBtn"
            @click="handleConfirm"
            hidden = "true"
          >确认</el-button> -->
           <el-button
            type="primary"
            size="small"
            v-if="permissionList.adjustBtn"
            @click="handleUpdateBatchAdjustReason"
          >调整说明</el-button> 
          <el-button
            @click="exportClick"
            v-if="permissionList.exportBtn"
          >导出</el-button>
        </template>
        <template
          slot="menu"
          slot-scope="scope"
        >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="permissionList.editBtn && (scope.row.operators != '合计' && scope.row.lineCode != '小计')"
            @click="handleUpdateItem(scope.row,scope.index)"
          >编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            v-if="false"
            :disabled="!scope.row.attachment"
            @click="handleDownloadItemAtt(scope.row,scope.index)"
          >下载附件
          </el-button>
        </template>
      </avue-crud>
      <el-dialog
        title="编辑"
        :visible="!!target"
        :destroy-on-close="true"
        :before-close="closeEdit"
      >
        <avue-form
          ref="form"
          v-model="target"
          :option="formOption"
          @submit="submitUpdateItem"
        >
        <!-- <template
            slot-scope="scope"
            slot="attachment"
          >
            <el-upload
              class="upload-demo"
              action="/admin/sys-file/upload"
              :limit="1"
              :headers="headers"
              :on-success="upsucc"
              :on-remove="handleRemove"
              :file-list="fileList"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </template> -->
        </avue-form>
      </el-dialog>
      <el-dialog
        title="调整说明"
        :visible="updateBatchAdjustReasonDialog"
        @close="closeReasonDlg"	
      >
        <avue-form
          ref="reasonForm"
          v-model="reasonForm"
          :option="updateAdjustReasonOption"
          @submit="submitUpdateBatchAdjustReason"
          @reset-change="fileAddressRest"
        >
          <!-- <template
            slot-scope="scope"
            slot="attachment"
          >
            <el-upload
              class="upload-demo"
              action="/admin/sys-file/upload"
              :limit="1"
              :headers="headers"
              :on-success="upsucc"
              :on-remove="handleRemove"
              :file-list="fileList"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </template> -->
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, getObj, confirm, dataExport, updateBatch, updateById } from '@/api/rca/swckdiffafterclear'
import { tableOption, formOption, updateAdjustReasonOption } from '@/const/crud/rca/swckdiffafterclear'
import { handleExcelResponse, getQueryString, handleDownFile, deepClone } from '@/util/util';
import { mapGetters } from 'vuex'
import store from '@/store';
import report from './components/report.vue';
import {handleDownloadZip} from '@/util/util.js';

export default {
  name: 'swckdiffafterclear',
  components: {
    report,
  },
  data () {
    return {
      searchForm: {
        startDate:"",
        endDate:"",
        startClearDate:"",
        endClearDate:"",
      },
      extraParam: {
        diffMoneyStart: undefined,
        diffMoneyEnd: undefined
      },
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      selection: [],

      showReport: false,
      target: null,
      updateBatchAdjustReasonDialog: false,
      formOption: formOption,
      updateAdjustReasonOption: updateAdjustReasonOption,
      fileList: [],
      fileAddress: null,

      reasonForm: {
        currClearDate: undefined,
        ticketType: undefined,
        adjustReason: undefined,
        attachment: undefined
      }
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    headers () {
      return {
        "Authorization": 'Bearer ' + store.getters.access_token
      }
    },
    permissionList () {
      return {
        viewReportBtn: this.vaildData(this.permissions.sw_ck_diff_after_clear_report, false),
        confirmBtn: this.vaildData(this.permissions.sw_ck_diff_after_clear_confirm, false),
        editBtn: this.vaildData(this.permissions.sw_ck_diff_after_clear_edit, false),
        adjustBtn: this.vaildData(this.permissions.sw_ck_diff_after_clear_adjust, false),
        editBatchBtn: this.vaildData(this.permissions.sw_ck_diff_after_clear_edit_batch, false),
        exportBtn: this.vaildData(this.permissions.sw_ck_diff_after_clear_export, false),
      };
    }
  },
  methods: {
    selectionChange (list) {
      this.selection = list.map(l => l.id);
    },
    getList (page, params) {
      this.tableLoading = true
      const [startDate, endDate] = this.searchForm.cleanTime || [];
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm,{startDate,endDate}, { ...this.extraParam })).then(response => {
        this.tableData = response.data.data
        //this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    async searchChange (form, done) {
      this.searchForm = { ...form };
      const [startDate, endDate] = this.searchForm.cleanTime || [];
      if (!startDate || !endDate) {
        this.$message.error("周期不能为空");
        done();
        return;
      }
      // const { ticketType } = this.searchForm
      // if ([null, undefined].includes(ticketType)) {
      //   this.$message.error('票种不能为空')
      //   done();
      //   return;
      // }
      try {
        await this.getList(this.page, this.searchForm);
      } finally {
        done();
      }
    },
    refreshChange () {
      this.getList(this.page)
    },
    async exportClick () {
      this.dataExport();
    },
    async dataExport () {
      const [startDate, endDate] = this.searchForm.cleanTime || [];
      if (!startDate || !endDate) {
        this.$message.error("周期不能为空");
        return;
      }
      // if ([null, undefined].includes(ticketType)) {
      //   this.$message.error('票种不能为空')
      //   return
      // }
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      })
      try {
        const res = await dataExport(Object.assign({}, {startDate,endDate}, this.searchForm, { ...this.extraParam }));
        handleExcelResponse(res);
      } finally {
        loading.close();
      }
    },
    handleUpdateBatchAdjustReason () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要批量修改调整说明的数据');
        return;
      }
      this.updateBatchAdjustReasonDialog = true
    },
    async submitUpdateBatchAdjustReason (form, done) {
      const {
        selection, tableData, fileAddress
      } = this;
      const { currClearDate, ticketType, adjustReason , attachment} = form;
      const params = tableData.filter(data => selection.includes(data.id)).map(data => {
        const obj = deepClone(data);
        Object.assign(obj, {
          currClearDate, ticketType, adjustReason, attachment ,adjustStatus:'1'
        })
        if (fileAddress) {
          Object.assign(obj, {
            attachment: fileAddress
          })
        }
        return obj
      })

      const data = await updateBatch(params);
      if (data) {
        this.$message.success('操作成功');
        this.closeReasonDlg();
      } else {
        this.$message.error('操作失败，请联系管理员');
      }

      this.getList(this.page)
      done()
    },
    fileAddressRest () {
      this.fileAddress = undefined;
      this.fileList = [];
    },
    closeReasonDlg () {
      this.fileAddressRest();
      this.reasonForm = {
        currClearDate: undefined,
        ticketType: undefined,
        adjustReason: undefined,
        attachment: undefined
      };
      this.updateBatchAdjustReasonDialog = false;
    },
    upsucc (response, file, fileList) {
      this.fileAddress = response.data.bucketName + "-" + response.data.fileName;
      console.log(this.fileAddress + "上传成功");
    },
    handleRemove (file, fileList) {
      this.fileAddress = null;
      console.log(this.fileAddress + "移除成功");
    },
    handleConfirm: function () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要确定的数据');
        return;
      }
      confirm({
        ids: this.selection,
      }).then(data => {
        this.$message.success('确定成功')
        this.getList(this.page)
      })
    },
    searchReset () {
      this.page.currentPage = 1;
      this.extraParam = {
        diffMoneyStart: undefined,
        diffMoneyEnd: undefined
      };
      this.getList(this.page);
    },
    async submitUpdateItem (params, done) {
      const {
        selection, tableData, fileAddress
      } = this;
      const { currClearDate, ticketType, adjustReason , attachment} = params;

      const obj = {
        ...params,
        currClearDate, ticketType, adjustReason, attachment
      }
      const data = await updateById(obj);
      if (data) {
        this.$message.success('操作成功');
        this.$nextTick(()=>{
          this.closeEdit()
        })
      } else {
        this.$message.error('操作失败，请联系管理员');
      }
      this.getList(this.page)
      done()
    },
    // async submitUpdateItem (params, done) {
    //   const { fileAddress } = this
    //   const { diffMoney, currClearMoney, lastClearMoney } = params;
    //   const obj = {
    //     ...params,
    //     diffMoney: diffMoney * 100,
    //     currClearMoney: currClearMoney * 100,
    //     lastClearMoney: lastClearMoney * 100,
    //   }
    //   if (fileAddress) {
    //     Object.assign(obj, {
    //       attachment: fileAddress
    //     })
    //   }
    //   const data = await updateById(obj);
    //   if (data) {
    //     this.$message.success('操作成功');
    //     this.$nextTick(()=>{
    //       this.closeEdit()
    //     })
    //   } else {
    //     this.$message.error('操作失败，请联系管理员');
    //   }
    //   done()
    // },
    closeEdit () {
      this.target = null;
      this.fileAddressRest();
    },
    handleUpdateItem (row, index) {
      this.fileAddressRest();
      const { diffMoney, currClearMoney, lastClearMoney } = row;
      this.target = { ...row, diffMoney: diffMoney / 100, currClearMoney: currClearMoney / 100, lastClearMoney: lastClearMoney / 100 }
      if (row.attachment) {
        this.fileList = [{
          name: row.attachment,
          url: row.attachment,
        }];
        this.fileAddress = row.attachment;
      }
    },
    handleDownloadItemAtt(row, index) {
      let pathList = [];
      if (!this.validatenull(row.attachment)) {
        pathList.push(row.attachment);
      }
      if (pathList.length == 0) {
        this.$message.info("没有附件下载！");
        return;
      }
      handleDownloadZip(pathList, "清分后数据差异附件.zip");
    },
    // handleDownloadItemAtt (row, index) {
    //   const { attachment } = row
    //   if (!attachment) {
    //     this.$message.warning("没有附件下载！");
    //     return;
    //   }
    //   let loading = this.$loading({
    //     lock: true,
    //     text: "Loading",
    //     spinner: "el-icon-loading",
    //     background: "rgba(0, 0, 0, 0.7)"
    //   })
    //   try {
    //     handleDownFile(attachment);
    //   } finally {
    //     loading.close();
    //   }
    // },
  }
}
</script>
